//
//  HomeTableViewController.swift
//  Weibo
//
//  Created by 张远文 on 16/4/25.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit
import SVProgressHUD

private let homeCellId = "HomeCellId"

//cell到倒数第几个开始加载更多数据 取值从 0 开始
private let updatenum = 0

class HomeTableViewController: BaseTableViewController {

    //数据源 模型数组
    private lazy var statuses = [Status]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        if !userLogin {
            visitorLoginView?.setUIInfo(nil, title: "惊喜关注一些人,回这里看看有什么惊喜")
            return
        }
        
        //准备tableview
        prepareTableView()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        //获取网络数据
        loadData()
    }
    
    private func prepareTableView() {
        //设置下拉刷新
        refreshControl = UIRefreshControl()
        
        //添加监听方法
        refreshControl?.addTarget(self, action: #selector(loadData), forControlEvents: .ValueChanged)
        //注册cell
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: homeCellId)
        
        //tableview 在ios8 中自动计算防高 需要指定两个属性
        //预估行高
        tableView.estimatedRowHeight = 200
        //需要指定自动计算行高
        //要使用自动计算行高 必须有一个自上而下的约束
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //设置分割线
        tableView.separatorStyle = .None
        
        //设置指示器
        tableView.tableFooterView = indicatorView
    }
    
    //MARK: - 加载首页数据
    @objc private func loadData() {
        
        //确认since_id
        //注意max_id 和 since_id 同时有值时 服务器不会给任何数据
        var since_id = 0
        var max_id = 0
        
        if indicatorView.isAnimating() {
            //加载更多
            since_id = 0
            max_id = statuses.last?.id ?? 0
            
        } else {
            //上拉刷新
            max_id = 0
            since_id = statuses.first?.id ?? 0
        }
        
        StatusListViewModel.loadData(since_id: since_id, max_id: max_id) { (array) in
            //打印更新数据的数组
            print(array?.count)
            
            self.refreshControl?.endRefreshing()
            
            if array == nil {
                //请求失败
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                self.indicatorView.stopAnimating()
                return
            }
            
            //拿到数据赋值
            if since_id > 0 {
                //下拉刷新 直接追加数据
                self.statuses = array! + self.statuses
                
            } else if max_id > 0 {
                //上拉加载更多
                self.statuses += array!
                self.indicatorView.stopAnimating()
                
            } else {
                //第一次加载数据
                self.statuses = array!
            }
            
            //刷新表格
            self.tableView.reloadData()
        }
    }
    
    //加载更多的指示器
    private lazy var indicatorView: UIActivityIndicatorView = {
       
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        
        return indicatorView
    }()
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statuses.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(homeCellId, forIndexPath: indexPath) as! StatusCell

        // Configure the cell...
        cell.status = statuses[indexPath.row]
        
        if indexPath.row == statuses.count - 1 - updatenum && !indicatorView.isAnimating() {
            
            indicatorView.startAnimating()
            loadData()
            print("静默加载数据")
        }
        
        return cell
    }
 

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
